package com.zaizai.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.zaizai.domain.*;
import com.zaizai.domain.dto.CommodityDto;
import com.zaizai.domain.dto.OrderCommodityDto;
import com.zaizai.domain.vo.OrderCommdityVO;
import com.zaizai.domain.vo.OrderVO;
import com.zaizai.mapper.OrderMapper;
import com.zaizai.service.IDepartmentService;
import com.zaizai.service.IOrderService;
import com.zaizai.service.IRoleService;
import com.zaizai.utils.BaseContext;
import com.zaizai.websocket.OrderNotificationHandler;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

/**
 * 订单Service业务层处理
 *
 * @author zaiZai
 * @date 2024-10-21
 */
@Slf4j
@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderCommdityServiceImpl orderCommdityService;
    @Autowired
    private CommodityServiceImpl commodityService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IDepartmentService departmentService;

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public Order selectOrderById(Long id) {
        log.info("Selecting order by id: {}", id);
        try {
            Order order = orderMapper.selectOrderById(id);
            log.info("Found order: {}", order);
            if (order != null && order.getItems() == null) {
                order.setItems(new ArrayList<>());
            }
            return order;
        } catch (Exception e) {
            log.error("Error selecting order by id:", e);
            return null;
        }
    }

    /**
     * 查询订单列表
     *
     * @param order 订单
     * @return 订单
     */
    @Override
    public List<Order> selectOrderList(Order order) {
        log.info("Selecting order list with params: {}", order);
        try {
            List<Order> orders = orderMapper.selectOrderList(order);
            log.info("Found {} orders", orders.size());
            return orders;
        } catch (Exception e) {
            log.error("Error selecting order list:", e);
            return new ArrayList<>();
        }
    }

    /**
     * 新增订单
     *
     * @param orderDto 订单
     * @return 结果
     */
    @Override
    @Transactional
    public int insertOrder(OrderCommodityDto orderDto) {
        // 计算总价
        int totalPrice = 0;
        List<CommodityDto> commodityList = orderDto.getCommodityList();
        
        // 检查用户是否存在
        Role role = roleService.selectRoleById(orderDto.getRoleId());
        if (role == null) {
            throw new RuntimeException("用户不存在");
        }

        // 检查并更新库存
        for (CommodityDto commodity : commodityList) {
            totalPrice += commodity.getPrice() * commodity.getBuyCount();

            // 更新库存信息
            Commodity c = commodityService.selectCommodityById(commodity.getId());
            if (c == null) {
                throw new RuntimeException("商品不存在");
            }
            if (c.getInventory() < commodity.getBuyCount()) {
                throw new RuntimeException("商品库存不足");
            }
            c.setInventory(c.getInventory() - commodity.getBuyCount());
            commodityService.updateCommodity(c);
        }

        // 创建订单
        Order order = new Order();
        order.setOrderId("ORDER" + System.currentTimeMillis());
        order.setTelephone(orderDto.getTelephone());
        order.setRoleId(orderDto.getRoleId());
        order.setRoleName(orderDto.getRoleName());
        order.setDepartmentId(role.getDepartmentId());
        order.setScheduledTime(new Date());
        order.setStatus(0);
        order.setTotalPrice((long) totalPrice);
        order.setCreateTime(new Date());

        // 插入订单
        orderMapper.insertOrder(order);

        // 发送WebSocket通知
        try {
            OrderNotificationHandler.broadcastNewOrder(order);
        } catch (Exception e) {
            log.error("发送订单通知失败", e);
        }

        // 插入订单商品
        for (CommodityDto commodity : commodityList) {
            OrderCommdity orderCommdity = new OrderCommdity();
            orderCommdity.setOrderId(order.getId());
            orderCommdity.setCommodityName(commodity.getName());
            orderCommdity.setBuyCount(commodity.getBuyCount());
            orderCommdity.setPrice(commodity.getPrice());
            orderCommdity.setTotalPrice(commodity.getPrice() * commodity.getBuyCount());
            orderCommdityService.insertOrderCommdity(orderCommdity);
        }
        return 1;
    }

    /**
     * 修改订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int updateOrder(Order order) {
        //根据当前登录人的角色身份来存储处理人员
        Long userId = BaseContext.getCurrentId();
        Role role = roleService.selectRoleById(userId);
        //不是客户，设置处理人员为当前登录人
        if(role.getPermission() != 0){
            order.setStaffName(role.getUserName());
        }

        return orderMapper.updateOrder(order);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderByIds(Long[] ids) {
        return orderMapper.deleteOrderByIds(ids);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderById(Long id) {
        return orderMapper.deleteOrderById(id);
    }


    /**
     * 获取订单VO列表
     * @param order
     * @return
     */
    @Override
    public List<OrderVO> getOrderVOList(Order order) {
        // 查询订单列表
        List<Order> orderList = orderMapper.selectOrderList(order);
        // 创建订单VO列表
        List<OrderVO> orderVOList = new ArrayList<OrderVO>();
        for (Order o : orderList) {

            OrderVO orderVO = new OrderVO();
            // 复制属性
            BeanUtils.copyProperties(o, orderVO);
            // 下单人邮箱
            orderVO.setRoleEmail(roleService.selectRoleById(o.getRoleId()).getEmail());
            // 设置状态
            Integer status = o.getStatus();
            if(status == 0){orderVO.setStatus("待处理");
            } else if (status == 1) {
                orderVO.setStatus("已完成");
            }else{
                orderVO.setStatus("已取消");
            }
            // 查询订单对应的商品列表
            List<OrderCommdity> orderCommdityList = orderCommdityService.selectOrderCommdityList(new OrderCommdity().builder().orderId(o.getId()).build());
            List<OrderCommdityVO> orderCommdityVOList = new ArrayList<OrderCommdityVO>();
            for (OrderCommdity orderCommdity : orderCommdityList) {
                OrderCommdityVO orderCommdityVO = new OrderCommdityVO();
                BeanUtils.copyProperties(orderCommdity, orderCommdityVO);
                // 设置订单编号
                orderCommdityVO.setOrderId(o.getOrderId());
                orderCommdityVOList.add(orderCommdityVO);
            }
            orderVO.setOrderCommdityVOList(orderCommdityVOList);
            orderVOList.add(orderVO);
        }
        return orderVOList;
    }

}
